package com.codeduck.async.controller;

import com.codeduck.async.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2021-12-26
 */
@RestController
@Slf4j
public class IndexController {

    @Resource
    private TaskService taskService;


    /**
     * 异步方法测试：所需执行的任务要耗时2s，被调用的方法顺序且非阻塞式执行
     */
    @GetMapping("async")
    public String testAsync() {
        long start = System.currentTimeMillis();
        log.info("异步方法开始");

        taskService.asyncTask();

        log.info("异步方法结束");
        long end = System.currentTimeMillis();
        log.info("总耗时：{} ms", end - start);
        return "异步方法执行完毕，总耗时：" + (end - start) +  " ms";
    }

    /**
     * 同步方法测试：所需执行的任务要耗时2s，被调用的方法顺序且阻塞式执行
     */
    @GetMapping("sync")
    public String testSync() {
        long start = System.currentTimeMillis();
        log.info("同步方法开始");

        taskService.syncTask();

        log.info("同步方法结束");
        long end = System.currentTimeMillis();
        log.info("总耗时：{} ms", end - start);
        return "同步方法执行完毕，总耗时：" + (end - start) +  " ms";
    }
}
